import { querySQLApi, getDataTableApi, getDataTableColumnApi } from '@/api/customReport'

const custom = {
  namespaced: true,
  state: {
   dataList: [],
   tableList: [],
   columns: [],
   filterColumns: []
  },
  mutations: {
    SET_DATA_LIST: (state, list) => {
      state.dataList = list
    },
    SET_TABLE_LIST: (state, list) => {
      state.tableList = list
    },
    SET_TABLE_COLUMNS: (state, columns) => {
      state.columns = columns.map( v => {
        return  {
          title: v,
          dataIndex: v,
        }
      })
    },
    SET_FILTER_COLUMNS: (state, arr) => {
      state.filterColumns = arr
    }
  },
  actions: {
    // 获取数据库的列
    getDataColumnsList ({ commit },id) {
      return new Promise((resolve, reject) => {
        getDataTableColumnApi(id)
          .then(res => {
            if (res.code == 0) {
              resolve(res)
            } else {
              reject(res)
            }
          })
          .catch(err => {
            console.error(err)
            reject(err)
          })
      })
    },
    // 获取指定数据源的数据库
    getDataList ({ commit },id) {
      return new Promise((resolve, reject) => {
        getDataTableApi(id)
          .then(res => {
            if (res.code == 0) {
              const { data } = res
              commit('SET_DATA_LIST',data)
              resolve(res)
            } else {
              reject(res)
            }
          })
          .catch(err => {
            console.error(err)
            reject(err)
          })
      })
    },
    searchSQLQuery ({commit}, sql) {
      return new Promise((resolve, reject) => {
        querySQLApi({...sql})
          .then(res => {
            if (res.code == 0) {
              commit('SET_TABLE_LIST',res.data.result)
              commit('SET_TABLE_COLUMNS',res.data.columns)
              resolve(res)
            } else {
              reject(res)
            }
          })
          .catch(err => {
            console.error(err)
            reject(err)
          })
      })

    }
  },
  getters: {

  },
}

export default custom